package leetcode.editor.cn;

public class _238_ProductOfArrayExceptSelf {
    public static void main(String[] args) {
        Solution solution = new _238_ProductOfArrayExceptSelf().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    // O(n) 空间
    class Solution1 {
        public int[] productExceptSelf(int[] nums) {
            int n = nums.length;
            int[] L = new int[n];
            int[] R = new int[n];
            L[0] = R[n - 1] = 1;
            for (int i = 1; i < n; i++) {
                L[i] = L[i - 1] * nums[i - 1];
            }
            for (int i = n - 2; i >= 0; i--) {
                R[i] = R[i + 1] * nums[i + 1];
            }
            int[] res = new int[n];
            for (int i = 0; i < n; i++) {
                res[i] = L[i] * R[i];
            }
            return res;
        }
    }

    // O(1) 空间
    class Solution {
        public int[] productExceptSelf(int[] nums) {
            int n = nums.length;
            int[] res = new int[n];
            res[0] = 1;
            for (int i = 1; i < n; i++) {
                res[i] = res[i - 1] * nums[i - 1];
            }
            int r = nums[n - 1];
            for (int i = n - 2; i >= 0; i--) {
                res[i] *= r;
                r *= nums[i];
            }
            return res;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}